package info.hexin.jdk.socket.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

/**
 * Created by infi.he on 2015/4/27.
 */
public class EchoAioServer {
    private final static int port = 8000;
    private final static String attachment = "StringTest";

    public static void main(String args[]) {
        new EchoAioServer();
    }

    public EchoAioServer() {
        listen();
    }

    private void listen() {
        try {

            AsynchronousChannelGroup threadGroup = AsynchronousChannelGroup
                    .withThreadPool(Executors.newFixedThreadPool(20));
            try (AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(threadGroup)) {
                server.bind(new InetSocketAddress(port));
                System.out.println("Echo listen on " + port);
                server.accept(attachment, new CompletionHandler<AsynchronousSocketChannel, Object>() {
                    public void completed(AsynchronousSocketChannel ch, Object attachment) {
                        System.out.println("attachment>>>>" + attachment);
                        System.out.println("waiting ....");
                        // accept the next connection
                        server.accept(attachment, this);
                        // handle this connection
                        handle(ch);
                        System.out.println("done...");

                    }

                    @Override
                    public void failed(Throwable exc, Object attachment) {
                        System.out.println("server failed: " + exc);
                    }
                });

                try {
                    // Wait for ever
                    Thread.sleep(Integer.MAX_VALUE);
                } catch (InterruptedException ex) {
                    System.out.println(ex);
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    private void handle(AsynchronousSocketChannel ch) {
//        ByteBuffer.allocateDirect()
//        ch.read()
    }
}
